package com.mazaiting.imqq.presenter.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.Toast;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.ConnectStatusChangeListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import com.mazaiting.imqq.model.bean.UserInfo;
import com.orhanobut.logger.Logger;

/**
 * 连接服务器服务
 */
public class ConnectService extends Service {

  public ConnectService() {
    UserInfo userInfo = BmobUser.getCurrentUser(UserInfo.class);
    if (!TextUtils.isEmpty(userInfo.getObjectId())) {
      BmobIM.connect(userInfo.getObjectId(), new ConnectListener() {
        @Override public void done(String s, BmobException e) {
          if (e == null) {
            //连接成功
            Logger.e("连接成功");
            Toast.makeText(ConnectService.this, "连接成功", Toast.LENGTH_SHORT).show();
          } else {
            //连接失败
            Toast.makeText(ConnectService.this, e.getMessage(), Toast.LENGTH_SHORT).show();
          }
        }
      });
    }
  }

  @Override public int onStartCommand(Intent intent, int flags, int startId) {
    runThread();
    return super.onStartCommand(intent, flags, startId);
  }

  private void runThread() {
    new Thread(new Runnable() {
      @Override public void run() {
        try {
          Thread.sleep(10000);
          Logger.e(BmobIM.getInstance().getCurrentStatus().getMsg());
          runThread();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();
  }

  @Override public void onDestroy() {
    super.onDestroy();
    BmobIM.getInstance().disConnect();
  }

  @Override public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
  }
}
